package com.group2.view;
import java.awt.Font;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.event.*;
import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableModel;
import javax.swing.table.TableRowSorter;

import java.awt.*;
import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;

import model.*;
import static model.netBase.IP;
public class ShopShowFrame_Admin extends JFrame {

	private ArrayList<Goods> goods;

	public ShopShowFrame_Admin() 
	{init();}
    //刷新表格获取所有商品
	public void reFresh(JTable table){
        Object[] columnNames = {"编号","图片","品名","种类","价格","剩余量"};
        try {
            Socket socket = new Socket(IP(), 2000);
            socket.setSoTimeout(3000);
            //构建IO
            OutputStream os = socket.getOutputStream();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
            bw.write("51" + '\n');
            bw.flush();
            InputStream is = socket.getInputStream();
            ObjectInputStream ois = new ObjectInputStream(is);
            goods = (ArrayList<Goods>) ois.readObject();
            socket.close();
        } catch (UnknownHostException a) {
            throw new RuntimeException(a);
        } catch (IOException a) {
            throw new RuntimeException(a);
        } catch (ClassNotFoundException a) {
            throw new RuntimeException(a);
        }
        Object[][]rowData=new Object[goods.size()][6];
        for (int x = 0; x < goods.size(); x++) {
            rowData[x][0] = goods.get(x).getId();
            String image = goods.get(x).getPicAddress();
            ImageIcon icon = new ImageIcon((UserLogOnFrame.class.getResource(image)));
            rowData[x][1] = icon;
            rowData[x][2] = goods.get(x).getGoodsname();
            rowData[x][3] = goods.get(x).getGoodsstyle();
            rowData[x][4] = goods.get(x).getPrice();
            rowData[x][5] = goods.get(x).getSurplus();
        }

        // 创建 表格模型，指定 所有行数据 和 表头
        DefaultTableModel tableModel = new DefaultTableModel(rowData, columnNames) {
            public Class<?> getColumnClass(int columnIndex) {
                return getValueAt(0, columnIndex).getClass();
            }
            @Override
            public boolean isCellEditable(int row,int column){
                return false;
            }//设置不可修改
        };
        table.setModel(tableModel);
        //设置筛选条
        RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel);
        table.setRowSorter(rowSorter);
    }
    public void init() {

    	Font f = new Font("黑体", Font.PLAIN, 15);
    	Font d = new Font("黑体", Font.BOLD, 17);
    	this.setTitle("欢迎管理员来到商店系统！");
    	this.setSize(530, 700);
    	this.setResizable(false);
        //jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
    	//ImageIcon icon = new ImageIcon("/images/add.png");
        // 创建内容面板，使用边界布局
        JPanel panel = new JPanel();
        JPanel panel2=new JPanel(null);
        JPanel panel0 =new JPanel(null);
        JLabel intro=new JLabel("当前商店内全部商品信息如下：");
        JLabel instr=new JLabel("请输入需要管理的商品种类：");
        JTextField search=new JTextField("");
        
        intro.setFont(d);
        instr.setFont(f);
        JButton addRow= new JButton("增加商品");
        addRow.setFont(f);
        addRow.setFocusPainted(false);
        JButton deleteRow=new JButton("删除商品");
        deleteRow.setFont(f);
        deleteRow.setFocusPainted(false);
        JButton Search =new JButton();
        Search.setFocusPainted(false);
        Search.setIcon(new ImageIcon(UserLogOnFrame.class.getResource("/images/search.png")));


       
        panel0.setBounds(0,0,450,100); 
        intro.setBounds(50,10, 300, 30);  
        instr.setBounds(50,50, 200, 30);
        search.setBounds(250,50,100,30);
        Search.setBounds(350,50,30,30);
        panel.setBounds(40,100,450,300);
         
        
        panel2.setBounds(0,400, 550, 200);
 
        addRow.setBounds(50,500, 100, 30);
        deleteRow.setBounds(350,500, 100, 30);

        JTable table = new JTable();
        // 表头（列名）
        reFresh(table);

        // 设置表格内容颜色
        table.setForeground(Color.BLACK);                   // 字体颜色
        table.setFont(new Font(null, Font.PLAIN, 14));      // 字体样式
        table.setSelectionForeground(Color.DARK_GRAY);      // 选中后字体颜色
        table.setSelectionBackground(Color.LIGHT_GRAY);     // 选中后字体背景
        table.setGridColor(Color.GRAY);                     // 网格颜色

        // 设置表头
        table.getTableHeader().setFont(f);  // 设置表头名称字体样式
        table.getTableHeader().setForeground(Color.blue);                // 设置表头名称字体颜色
        table.getTableHeader().setResizingAllowed(false);               // 设置不允许手动改变列宽
        table.getTableHeader().setReorderingAllowed(false);             // 设置不允许拖动重新排序各列

        // 设置行高
        table.setRowHeight(95);
 
        // 第一列列宽设置为40
        table.getColumnModel().getColumn(0).setPreferredWidth(20);
        table.getColumnModel().getColumn(1).setPreferredWidth(60);

        // 设置滚动面板视口大小（超过该大小的行数据，需要拖动滚动条才能看到）
        table.setPreferredScrollableViewportSize(new Dimension(400, 280));

        // 把 表格 放到 滚动面板 中（表头将自动添加到滚动面板顶部）
        JScrollPane scrollPane = new JScrollPane(table);
       
        // 添加 滚动面板 到 内容面板
        panel.add(scrollPane);
        
        panel2.add(addRow);
        panel2.add(deleteRow);
        panel0.add(intro);
        panel0.add(instr);
        panel0.add(search);
        panel0.add(Search);

        // 设置 内容面板 到 窗口  
        this.getContentPane().add(panel0);
        this.getContentPane().add(panel);
        this.getContentPane().add(panel2);
      
        Search.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
            	if(search.getText().equals("")) {JOptionPane.showMessageDialog(null, "请输入内容");}
            	else
            	{	try {
                    Socket socket=new Socket(IP(),2000);
                    socket.setSoTimeout(3000);
                    //构建IO
                    OutputStream os = socket.getOutputStream();
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                    bw.write("54"+'\n'+search.getText()+'\n');
                    bw.flush();
                    InputStream is = socket.getInputStream();
                    ObjectInputStream ois = new ObjectInputStream(is);
                    Object obj = ois.readObject();
                    goods.clear();
                    goods=(ArrayList<Goods>) obj;
                    System.out.println(goods);
                    //构建表格
                    socket.close();
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                } catch (SocketException ex) {
                    throw new RuntimeException(ex);
                } catch (UnknownHostException ex) {
                    throw new RuntimeException(ex);
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                }
                    if(goods.size()>0) {
                        Object[][]rowData1=new Object[50][6];
                        for (int y = 0; y < goods.size(); y++) {
                            rowData1[y][0] = goods.get(y).getId();
                            String image = goods.get(y).getPicAddress();
                            ImageIcon icon = new ImageIcon((UserLogOnFrame.class.getResource(image)));
                            rowData1[y][1] = icon;
                            rowData1[y][2] = goods.get(y).getGoodsname();
                            rowData1[y][3] = goods.get(y).getGoodsstyle();
                            rowData1[y][4] = goods.get(y).getPrice();
                            rowData1[y][5] = goods.get(y).getSurplus();
                        }
                        Object[] columnNames = {"编号","图片","品名","种类","价格","剩余量"};
                        DefaultTableModel tableModel1 = new DefaultTableModel(rowData1, columnNames) {
                            public Class<?> getColumnClass(int columnIndex) {
                                return getValueAt(0, columnIndex).getClass();
                            }
                            @Override
                            public boolean isCellEditable(int row,int column){
                                return false;
                            }//设置不可修改
                        };
                        table.setModel(tableModel1);
                        //设置筛选条
                        RowSorter<TableModel> rowSorter = new TableRowSorter<TableModel>(tableModel1);
                        table.setRowSorter(rowSorter);
                    }
                    else{
                        JOptionPane.showMessageDialog(null, "查无此商品！");
                    }
                }
            }
        });
        addRow.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                new ShopAddFrame().addWindowListener(new WindowAdapter() {
                    @Override
                    public void windowClosed(WindowEvent e) {
                        System.out.println("运行到这");
                        reFresh(table);
                    }
                });
            }
        });
 
        deleteRow.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                int selectedRow = table.getSelectedRow();
                String id=goods.get(selectedRow).getId();
                try {
                    Socket socket=new Socket(IP(),2000);
                    socket.setSoTimeout(3000);
                    //构建IO
                    OutputStream os = socket.getOutputStream();
                    BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
                    bw.write("56\n"+id+'\n');
                    bw.flush();
                    socket.close();
                    JOptionPane.showMessageDialog(null, "删除成功！");
                } catch (UnknownHostException ex) {
                    JOptionPane.showMessageDialog(null, "删除失败！");
                    throw new RuntimeException(ex);
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null, "删除失败！");
                    throw new RuntimeException(ex);
                }
            }
        });
        this.setLocationRelativeTo(null);
        this.setVisible(true);
    }
    public static void main(String[] args) 
    {
    	new ShopShowFrame_Admin();
    	}
}
